//
// Created by Administrator on 2024/5/24.
//
#include <Logger.hpp>
#include <Common.hpp>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>

namespace NaturalEngine {
    const std::string pattern = "[%^%H:%M:%S:%e] [%P:%t][%^%l]%v%$";
    static std::vector<spdlog::sink_ptr> _sinks{};

    std::string GetCurrentDateStr(const char *fmt) {
        auto t = std::time(nullptr);
        auto tm = *std::localtime(&t);
        std::ostringstream oss;
        oss << std::put_time(&tm, fmt);
        return oss.str();
    }

    inline static void Init() {
        if (_sinks.size() > 0)return;
        auto stdout_color_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
        stdout_color_sink->set_pattern(pattern);
        stdout_color_sink->set_level(spdlog::level::trace);
        stdout_color_sink->set_color_mode(spdlog::color_mode::automatic);
        _sinks.push_back(stdout_color_sink);
        std::string date_str = GetCurrentDateStr("%Y-%m-%d");
        std::string time_str = GetCurrentDateStr("%H-%M-%S");
        std::string log_file_name = std::format("logs/{}/{}.log", date_str, time_str);
        auto basic_color_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(log_file_name);
        basic_color_sink->set_pattern(pattern);
        basic_color_sink->set_level(spdlog::level::trace);
        _sinks.push_back(basic_color_sink);
    }

    void Logger::log(LogLevel lvl, const memory_buf_t &buf) {
        auto LV = (spdlog::level::level_enum) (int) lvl;
        _logger->log(LV, string_view_t(buf.data(), buf.size()));
    }

    Logger::Logger(const std::string &tag) {
        Init();
        _logger = std::make_unique<spdlog::logger>(tag, _sinks.begin(), _sinks.end());
    }
}
